package com.zhuss.core.auth;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.zhuss.common.Bean;
import com.zhuss.common.StartSqlBo;
import com.zhuss.common.StartSqlVo;
import com.zhuss.core.db.dao.ext.ConfigDao;
import com.zhuss.util.JsonUtil;

@Aspect
@Component
public class SqlInfoAspect {
	
	public static ThreadLocal<List<String>> columnThread = new ThreadLocal<>();
	
	@Autowired
	private ConfigDao configDao;
	
	@Pointcut("execution(* com.zhuss.core.db.dao.ext.ConfigDao.startSql(..))")
	public void pointCut() {
		
	}
	
	@Pointcut("execution(* com.zhuss.core.processor.StartRead.startSql(..))")
	public void pointCut2() {
		
	}
	
	@Before("pointCut()")
	public void around(JoinPoint point) throws Throwable {
        Object[] arguments = point.getArgs();
        if (arguments.length <= 0) {
        	return;
        }
        StartSqlBo sqlBo = (StartSqlBo) arguments[0];
        String sql = sqlBo.getSql();
        int start = sql.indexOf(" t_");
        if (start > -1) {
        	String tableName = "";
        	char[] charList = sql.toCharArray();
        	char blank = ' ';
        	for (int i = start + 1; i < charList.length; i++) {
        		if (blank != charList[i]) {
        			tableName += charList[i];
        		} else {
        			break;
        		}
        	}
        	List<Object> objList = configDao.showColumn(tableName);
        	List<String> columnList = new ArrayList<>();
        	StringBuilder sub = new StringBuilder("");
        	int i = 0;
        	for (Object obj : objList) {
        		columnList.add(obj + "");
        		sub.append(obj + " " + "$cglib_prop_" + obj);
        		if (i < objList.size() - 1) {
        			sub.append(",");
        		}
        		i ++;
        	}
        	StringBuilder sqlBuilder = new StringBuilder(sql);
        	int index = sqlBuilder.indexOf("*");
        	sqlBuilder.insert(index + 1 , " " + sub.toString());
        	sqlBuilder.deleteCharAt(index);
        	columnThread.set(columnList);
        	sqlBo.setSql(sqlBuilder.toString());
        	
        }
    }
	
	@AfterReturning(pointcut="pointCut2()", returning="result")
	public void after(JoinPoint point, Object result) throws Throwable {
		StartSqlVo vo = (StartSqlVo)result;
		List<Map<String, Object>> mapList = vo.getMapList();
		List<String> columnList = columnThread.get();
		Bean bean = new Bean();
		bean.setColumnList(columnList);
		Bean dynamicBean = bean.dynamicExt();
		
		List<? extends Bean> result2 = JsonUtil.fromJsonList(JsonUtil.toJson(mapList), dynamicBean.getClass());
		vo.setResult(result2);
		vo.getMapList().clear();
    }
}
